package struts.factory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import struts.annotation.Controller;
import struts.annotation.RequestMapping;
import struts.util.StringUtil;

public class BeanFactory {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(BeanFactory.class);

	public static Map<String, Bean> getBean(String pack) throws Exception {
		Map<String, Bean> beans = new HashMap<String, Bean>();
		if (!StringUtil.isBlank(pack)) {
			String[] paths = pack.split(";");
			for (String path : paths) {
				Set<Class<?>> classSet = PackagesToScanUtil.getClasses(path);
				for (Class<?> clazz : classSet) {
					if (clazz.isAnnotationPresent(Controller.class)) {
						String classValue = null;
						if (clazz.isAnnotationPresent(RequestMapping.class)) {
							RequestMapping classRequestMapping = clazz.getAnnotation(RequestMapping.class);
							classValue = classRequestMapping.value();
						}
						Method[] methods = clazz.getMethods();
						for (Method method : methods) {
							if (method.isAnnotationPresent(RequestMapping.class)) {
								RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
								String value = classValue + requestMapping.value();
								if (!beans.containsKey(value)) {
									Bean bean = new Bean();
									bean.setClazz(clazz);
									bean.setMethodName(method.getName());
									bean.setMethodUrl(value);
									bean.setMethodAnnotations(method.getAnnotations());
									bean.setParameterTypes(method.getParameterTypes());
									bean.setReturnType(method.getReturnType());
									beans.put(value, bean);
									logger.info(bean);
								} else {
									throw new Exception(value + "已经存在:" + beans.get(value));

								}

							}
						}
					}
				}
			}
		}
		return beans;
	}

	public static Object createForm(Class<?> clazz, HttpServletRequest request) {
		logger.info("************** 装载" + clazz.getName() + "!*************");
		Object object = null;
		try {
			object = clazz.newInstance();

			Field[] propertys = clazz.getDeclaredFields();
			for (Field field : propertys) {
				stringToObject(field, object, request);
			}
		} catch (Exception e) {
			logger.info("**************FORM 装载失败!*************");
			logger.error(e);
		}
		return object;
	}

	public static void stringToObject(Field field, Object object, HttpServletRequest request) throws IllegalArgumentException, IllegalAccessException {
		field.setAccessible(true);
		String value = request.getParameter(field.getName());
		if (field.getType() == String.class) {
			field.set(object, value);
		} else if (field.getType() == Integer.class && !StringUtils.isBlank(value)) {
			field.set(object, Integer.parseInt(value));
		}
		field.setAccessible(false);
	}
}
